<template>
    <div class="container">
        <div class="conn">
            <el-button size="small" :type="isConnect ? 'success' : 'danger'" circle />
            <el-input v-model="wsUrl" size="small" :disabled="isConnect" placeholder="输入服务器地址"
                @keyup.enter.native="connectWebSocket" />
            <el-button type="primary" size="small" @click="connectWebSocket">{{ isConnect ? '断开' : '连接' }}</el-button>
        </div>
        <div class="chatBox">
            <div class="msgCard" v-for="item in msgList" :key="item.id">
                <div class="tooltips" v-if="item.type === '0'">
                    {{ item.time }} {{ item.message }}
                </div>
                <div class="userMsg" v-else>
                    <!-- 去掉日期保留时间 -->
                    <{{ item.time.slice(10) }}>
                        <span class="address">"{{ item.ip }}"</span> :
                        <span class="msg">{{ item.message }}</span>

                </div>

            </div>
        </div>
        <div class="sendBox">
            <el-input v-model="sendMsg" size="small" placeholder="输入消息" @keyup.enter.native="sendMessage" />
            <el-button type="primary" size="small" @click="sendMessage">发送</el-button>
        </div>
    </div>
</template>
<script setup>
import { Check, Close } from '@element-plus/icons-vue'
import { ref, onMounted, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
const isConnect = ref(false)
const socket = ref(null);
const wsUrl = ref('')
const sendMsg = ref('')
let localHost = window.location.host

const msgList = ref([])

const connectWebSocket = () => {
    if (isConnect.value) {
        socket.value?.close()
        isConnect.value = false
    } else {
        try {
            socket.value = new WebSocket('ws://' + wsUrl.value);
        } catch (error) {
            ElMessage.error({ message: '连接失败，检查服务器地址！', duration: 800 })
        }
        socket.value.onopen = function (event) {
            ElMessage.success({ message: '服务器已连接！', duration: 800 })
            isConnect.value = true
        };

        socket.value.onerror = function (error) {
            ElMessage.error({ message: '连接出错！', duration: 800 })
        };

        socket.value.onmessage = function (event) {
            let data = JSON.parse(event.data)
            if(data.type === 'all'){
                msgList.value = data.messages
            }
        };

        socket.value.onclose = function () {
            ElMessage.error({ message: '服务器已断开！', duration: 800 })
            isConnect.value = false
        };
    }
}
const sendMessage = () => {
    if (socket.value && socket.value.readyState === WebSocket.OPEN) {
        let obj = {
            type: 'message',
            msg: sendMsg.value,
            time: new Date().toLocaleString(),
        }
        socket.value.send(JSON.stringify(obj));
        sendMsg.value = ''
    } else {
        ElMessage.error({ message: '未连接服务器！', duration: 800 })
    }
}
// 监听menuList变化，输出111
// 使用Vue的nextTick来确保DOM更新后再执行滚动操作
watch(msgList, (newValue) => {
    nextTick(() => {
        let ele = document.querySelector('.chatBox');
        if (ele) {
            ele.scrollTop = ele.scrollHeight - ele.clientHeight;
        }
    });
});
</script>

<style lang="less" scoped>
.container {
    width: 100%;
    height: 100%;
    padding: 10px;
    // background: #fff;
    // border: 1px solid #333;
    border-radius: 10px;
    display: flex;
    flex-direction: column;

    .conn,
    .sendBox {
        -webkit-app-region: no-drag;
        width: 100%;
        height: 30px;
        display: flex;
        align-items: center;
        // margin-bottom: 5px;
        justify-content: space-between;

        .el-input {
            margin: 0 5px;
            flex: 1;
        }
    }

    .chatBox {
        flex: 1;
        // border: 1px solid #333;
        // border-radius: 10px;
        padding: 0 10px;
        overflow-y: scroll;
        overflow-x: hidden;

        &::-webkit-scrollbar {
            height: 5px;
            width: 5px;
        }

        &::-webkit-scrollbar-thumb {
            border-radius: 5px;
            background: #858585;
        }

        &::-webkit-scrollbar-track {
            border-radius: 5px;
            background: #f0f0f0;
        }

        .msgCard {
            color: #333;
            font-size: 12px;
            margin-bottom: 5px;
            width: 100%;

            .tooltips {
                width: 100%;
                color: red;
                text-align: center;
                font-size: 11px;
            }

            .userMsg {
                width: 100%;
                padding: 0 5px;
                border-radius: 5px;
                box-shadow: 0 0 2px #858585;
                font-size: 11px;
                color: #002f5d;

                .address {
                    font-weight: 700;
                }
                .msg{
                    -webkit-user-select: text;
                }
            }

        }

    }
}
</style>